package cn.wolfcode.springcloud.controller;


import cn.wolfcode.springcloud.domain.Order;
import cn.wolfcode.springcloud.service.IOrderService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("orders")
public class OrderController {


    @Autowired
    private IOrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //降级配置, 一旦这个方法异常或者超市, 走 fallbackMethod 指定降级方法
    @HystrixCommand(fallbackMethod = "saveFallback")
    @GetMapping("/save/{userId}/{productId}")   //使用Get 请求方式是为了让浏览器能发送请求
    public Object save(@PathVariable Long userId, @PathVariable Long productId, HttpServletRequest request){

      //String token = request.getHeader("token");
      //String cookie = request.getHeader("Cookie");
      //System.out.println("token"+token +"<---->" + "Cookie" + cookie);


        System.out.println("OrderController..save...");
       Order order = orderService.save(userId, productId);

        //记录调用日志
        log.info("OrderController-save.....");
        /*if(userId < 0){
            int i = 1/0;
        }*/
        return order;
    }

    //方法签名跟映射方法一样(方法名除外)
    //降级方法
    public Order saveFallback(@PathVariable Long userId, @PathVariable Long productId,HttpServletRequest request){
        System.out.println("走降级方法....");

        //通知程序员服务异常过来维护
        //发短信或者邮件
        //通过redis 控制频率
        new Thread(new Runnable() {
            @Override
            public void run() {
                String redisKey = "order-save";
                String value = stringRedisTemplate.opsForValue().get(redisKey);
                if(StringUtils.isEmpty(value)){
                    System.out.println("order下订单服务失败，请查找原因.");
                    stringRedisTemplate.opsForValue().set(redisKey,"save-order-fail",20, TimeUnit.SECONDS);
                }else{
                    System.out.println("已经发送过短信");
                }
            }
        }).start();

        return new Order() ;
    }
}
